﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;

namespace Matriculex.UI
{
    public class AjaxRequestOnlyAttribute : ActionMethodSelectorAttribute
    {
        public AjaxRequestOnlyAttribute(HttpVerbs verbs) : this(EnumToArray(verbs))
        {
        }

        public AjaxRequestOnlyAttribute(params string[] verbs)
        {
            if ((verbs == null) || (verbs.Length == 0))
            {
                throw new ArgumentException("Value cannot be null or empty.");
            }
            Verbs = new ReadOnlyCollection<string>(verbs);
        }

        private static void AddEntryToList(HttpVerbs verbs, HttpVerbs match, List<string> verbList, string entryText)
        {
            if ((verbs & match) != 0)
            {
                verbList.Add(entryText);
            }
        }

        internal static string[] EnumToArray(HttpVerbs verbs)
        {
            var verbList = new List<string>();
            AddEntryToList(verbs, HttpVerbs.Get, verbList, "GET");
            AddEntryToList(verbs, HttpVerbs.Post, verbList, "POST");
            AddEntryToList(verbs, HttpVerbs.Put, verbList, "PUT");
            AddEntryToList(verbs, HttpVerbs.Delete, verbList, "DELETE");
            AddEntryToList(verbs, HttpVerbs.Head, verbList, "HEAD");
            return verbList.ToArray();
        }

        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            string httpMethod = controllerContext.HttpContext.Request.HttpMethod;
            bool isAjaxRequest = controllerContext.HttpContext.Request.IsAjaxRequest();
            return isAjaxRequest && Verbs.Contains(httpMethod, StringComparer.OrdinalIgnoreCase);
        }

        // Properties
        public ICollection<string> Verbs { get; private set; }
    }
}